package com.allen.mk.admin.service.impl;

import com.allen.mk.admin.entity.SysRole;
import com.allen.mk.admin.entity.SysUser;
import com.allen.mk.admin.mapper.SysRoleMapper;
import com.allen.mk.admin.mapper.SysUserMapper;

import com.allen.mk.admin.service.SysUserService;
import response.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Allen
 * @since 2024-04-11
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Override
    public Result register(String username, String password) {
        try {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            SysUser user = userMapper.selectOne(queryWrapper.eq("user_name",username));
            if(user != null){
                return null;
            }else {
                SysUser user1 = new SysUser();
                user1.setUserName(username);
                user1.setPassword(new BCryptPasswordEncoder().encode(password));
                userMapper.insert(user1);
                return Result.success(user1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.failed("注册失败！");
    }

    @Override
    public List<SysRole> getAuthorities(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        SysUser user = userMapper.selectOne(queryWrapper.eq("user_name",username));
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return roleMapper.getAuthories(user.getId());
    }
}
